package com.ruoyi.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.domain.*;
import com.ruoyi.web.domain.query.AddTemporaryCheckQuery;
import com.ruoyi.web.domain.query.TemporaryCheckPageQuery;
import com.ruoyi.web.domain.vo.TemporaryCheckVO;
import com.ruoyi.web.mapper.BhPlansBillMapper;
import com.ruoyi.web.mapper.BhPlansMapper;
import com.ruoyi.web.mapper.BhReportMapper;
import com.ruoyi.web.mapper.BhRiskListMapper;
import com.ruoyi.web.service.TemporaryCheckService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class TemporaryCheckServiceImpl implements TemporaryCheckService {
    @Autowired
    private BhReportMapper bhReportMapper;
    @Autowired
    private BhPlansMapper bhPlansMapper;
    @Autowired
    private BhPlansBillMapper bhPlansBillMapper;
    @Autowired
    private BhRiskListMapper bhRiskListMapper;
    @Autowired
    private ISysUserService userService;

    /**
     * 新增临时作业检查
     *
     * @param addTemporaryCheckQuery 新增数据
     * @return 返回
     */
    @Transactional
    @Override
    public R<Void> addTemporaryCheck(AddTemporaryCheckQuery addTemporaryCheckQuery) {
        // 新增report数据
        BhReport addParam = new BhReport();
        BeanUtils.copyProperties(addTemporaryCheckQuery, addParam);
        addParam.setDelFlag(0);     // 0-未删除
        addParam.setStatus("0");    // 0-正常 1-关闭
        addParam.setInspectType(2); // 1-正常 2-临时
        addParam.setCreateTime(new Date());
        // 创建人
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long userId = loginUser.getUserId();
        addParam.setCreatedBy(String.valueOf(userId));
        if (bhReportMapper.insert(addParam) <= 0) {
            return R.fail("创建report失败！");
        }
        // 新增plan数据
        BhPlans addPlanParam = new BhPlans();
        BeanUtils.copyProperties(addTemporaryCheckQuery, addPlanParam);
        addPlanParam.setReportId(String.valueOf(addParam.getId()));
        addPlanParam.setDelFlag(0);
        addPlanParam.setCreateTime(new Date());
        addPlanParam.setTopId(-1);
        addPlanParam.setRiskStatus("1");
        addPlanParam.setCreatedBy(String.valueOf(userId));
        if (bhPlansMapper.insert(addPlanParam) <= 0) {
            return R.fail("创建plan失败！");
        }
        // 新增planBill数据
        BhPlans modPlanParam = new BhPlans();
        modPlanParam.setId(addPlanParam.getId());
        List<PlanBill> planBills = addTemporaryCheckQuery.getPlanBills();
        Integer hiddenDangerNum = 0;
        if (!CollectionUtils.isEmpty(planBills)) {
            modPlanParam.setCheckNum(planBills.size());
            for (PlanBill planBill : planBills) {
                String inspectResult = planBill.getInspectResult();
                if ("2".equals(inspectResult)) {
                    hiddenDangerNum++;
                }
                BhPlansBill addBillParam = new BhPlansBill();
                BeanUtils.copyProperties(planBill, addBillParam);
                addBillParam.setCreateTime(new Date());
                addBillParam.setDelFlag(0);
                addBillParam.setIsRectify("0");
                addBillParam.setPlanId(addPlanParam.getId());
                addBillParam.setReportId(String.valueOf(addParam.getId()));
                bhPlansBillMapper.insert(addBillParam);
            }
        }
        modPlanParam.setHiddenDangerNum(hiddenDangerNum);
        bhPlansMapper.updateById(modPlanParam);
        return R.ok();
    }

    /**
     * 获取临时作业检查分页数据
     *
     * @param temporaryCheckPageQuery 查询条件
     * @param pageQuery               分页参数
     * @return 临时作业检查分页数据
     */
    @Override
    public TableDataInfo<TemporaryCheckVO> getTemporaryCheckPage(TemporaryCheckPageQuery temporaryCheckPageQuery, PageQuery pageQuery) {
        QueryWrapper<TemporaryCheckPageQuery> wrapper = Wrappers.query();
        wrapper.eq("bp.del_flag", 0);
        wrapper.eq("bp.top_id", -1);
        wrapper.like(StringUtils.isNotBlank(temporaryCheckPageQuery.getConstructionOrganization()), "br.construction_organization", temporaryCheckPageQuery.getConstructionOrganization());
        wrapper.like(StringUtils.isNotBlank(temporaryCheckPageQuery.getWellNo()), "br.well_no", temporaryCheckPageQuery.getWellNo());
        wrapper.eq(StringUtils.isNotBlank(temporaryCheckPageQuery.getPersonInCharge()), "br.person_in_charge", temporaryCheckPageQuery.getPersonInCharge());
        // 处理作业项目查询条件
        String projectName = temporaryCheckPageQuery.getProjectName();
        if (StringUtils.isNotBlank(projectName)) {
            List<BhRiskList> bhRiskLists = bhRiskListMapper.selectList(new LambdaQueryWrapper<BhRiskList>().eq(BhRiskList::getDelFlag, 0).like(BhRiskList::getName, projectName).orderByAsc(BhRiskList::getId));
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(bhRiskLists)) {
                wrapper.and(i -> {
                    bhRiskLists.forEach(x -> {
                        i.or().apply("find_in_set({0},REPLACE(br.project_name, '|', ','))", x.getId());
                    });
                });
            }
        }
        Page<TemporaryCheckVO> result = bhPlansMapper.getTemporaryCheckPage(pageQuery.build(), wrapper);
        List<TemporaryCheckVO> temporaryCheckList = result.getRecords();
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(temporaryCheckList)) {
            temporaryCheckList.forEach(x -> {
                fillProjectName(x);
                fillName(x);
            });
        }
        return TableDataInfo.build(result);
    }

    // 填充作业项目
    private void fillProjectName(TemporaryCheckVO x) {
        List<String> ids = com.ruoyi.common.utils.StringUtils.str2List(x.getProjectName(), "[|]", true, true);
        List<BhRiskList> bhRiskLists = bhRiskListMapper.selectList(new LambdaQueryWrapper<BhRiskList>().in(com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(ids), BhRiskList::getId, ids).orderByAsc(BhRiskList::getId));
        x.setProjectName(bhRiskLists.stream().map(BhRiskList::getName).collect(Collectors.joining("|")));
    }

    // 填充执行人
    private void fillName(TemporaryCheckVO temporaryCheck) {
        List<String> names = new ArrayList<>();
        List<String> userIds = com.ruoyi.common.utils.StringUtils.str2List(temporaryCheck.getExecutors(), "[|]", true, true);
        if (!CollectionUtils.isEmpty(userIds)) {
            userIds.forEach(x -> {
                Long userId;
                try {
                    userId = Long.valueOf(x);
                    SysUser sysUser = userService.selectUserById(userId);
                    if (!Objects.isNull(sysUser)) {
                        names.add(sysUser.getNickName());
                    } else {
                        names.add(x);
                    }
                } catch (NumberFormatException e) {
                    names.add(x);
                }

            });
        }
        temporaryCheck.setExecutors(names.stream().reduce((s1, s2) -> s1 + "|" + s2).orElse(""));
    }

    /**
     * 获取临时作业检查详情
     *
     * @param id 临时作业检查id
     * @return 临时作业检查详情
     */
    @Override
    public R<TemporaryCheckVO> getTemporaryCheckDetail(Integer id) {
        TemporaryCheckVO result = bhPlansMapper.getTemporaryCheckDetail(id);
        fillProjectName(result);
        fillName(result);
        return R.ok(result);
    }
}
